<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { queryTodoList, completeTodo } from '@/api/todo.ts'
import { StorageEnum } from '@common/enums'
import type { TodoVO } from '@/interface'

const dataList = ref<TodoVO[]>([])
const loading = ref(false)
const userId = localStorage.getItem(StorageEnum.USER_ID)

const getTodoList = async () => {
  // 获取用户ID
  if (!userId) return
  loading.value = true
  const result = await queryTodoList({ createdBy: Number(userId) })
  loading.value = false
  if (!Array.isArray(result)) return
  // console.log(result)
  // 只获取前四条
  dataList.value = result.slice(0, 4)
}
onMounted(getTodoList)

const toggleTodo = async (id: number) => {
  await completeTodo({ id })
  await getTodoList()
}
</script>

<template>
  <el-scrollbar class="todo-component" height="300px" v-loading="loading">
    <div class="todo-container">
      <h3 class="title">待办事项</h3>
      <div class="todo-list">
        <div
          v-for="item in dataList"
          :key="item.id"
          class="todo-item"
          :class="{ completed: item.isEnd }"
        >
          <el-checkbox
            v-model="item.isEnd"
            :disabled="!!item.isEnd"
            @change="() => toggleTodo(item.id)"
          />
          <span class="todo-content">{{ item.title }}</span>
          <div class="todo-time" v-if="!item.isEnd">{{ item.stopAt }}</div>
          <el-button v-else link type="success" size="small">已完成</el-button>
        </div>
      </div>
    </div>
  </el-scrollbar>
</template>

<style scoped lang="scss">
.todo-component {
  width: 50%;
  height: 300px;
  //   padding: 0 24px;
  overflow: hidden;
  background-color: #1a1a1a;
  border-radius: 12px;
  color: #fff;
  border: 1px solid var(--xfxjLineColor);

  .todo-container {
    padding: 20px;

    .title {
      margin-bottom: 12px;
    }

    .todo-list {
      width: 100%;
      display: flex;
      flex-direction: column;
      gap: 12px;

      .todo-item {
        width: 100%;
        height: 44px;
        display: flex;
        align-items: center;
        padding: 10px;
        border: 1px solid var(--xfxjLineColor);
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          border: 1px solid #409eff;
        }

        .todo-content {
          flex: 1;
          margin: 0 10px;
        }

        .todo-time {
          color: #999;
        }

        &.completed {
          .todo-content {
            text-decoration: line-through;
            color: #999;
          }
        }
      }
    }
  }
}
</style>
